package com.ly.mssp.license.client.registry;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public final class GzipUtils {

	private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
			'e', 'f' };

	
	public static byte[] unzip(byte[] content){	
		ByteArrayInputStream in = null;
		GZIPInputStream ginzip = null;
		byte[] compressed = null;
		String decompressed = null;
		
		ByteArrayOutputStream out=new ByteArrayOutputStream();
		try {
			try{
				in = new ByteArrayInputStream(content);
				ginzip = new GZIPInputStream(in);
				try {
					byte[] buffer = new byte[1024];
					int offset = -1;
					while((offset = ginzip.read(buffer)) != -1){
						out.write(buffer,0,offset);
					}
					out.flush();
				}finally {
					ginzip.close();
					in.close();		
				}
				
				return out.toByteArray();
			}finally {
				out.close();
			}
		}catch(IOException e){
			e.printStackTrace();
			return null;
		}
	}

	public static byte[] zip(byte[] content){	
		ByteArrayInputStream in = null;
		GZIPOutputStream gzip = null;
		
		ByteArrayOutputStream out=new ByteArrayOutputStream();
		try {
			gzip=new GZIPOutputStream(out);
			try{				
		        try {
		            gzip.write(content);
		        }catch ( Exception e) {
		            e.printStackTrace();
		        }
		        return out.toByteArray();
			}finally {
				gzip.close();
				out.close();
				
			}
		}catch(IOException e){
			e.printStackTrace();
			return null;
		}
	}


	public static String blobSum(byte[] content) {
		if (content == null) {
			return null;
		}

		try {
			MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
			messageDigest.reset();
			messageDigest.update(content);
			return "sha256:" + getFormattedText(messageDigest.digest());
		} catch (Exception e) {
			return null;
		}
	}
	
	/**
	 *      * Takes the raw bytes from the digest and formats them correct.     
	 * * @param bytes the raw bytes from the digest.      * @return the formatted
	 * bytes.     
	 */
	private static String getFormattedText(byte[] bytes) {
		int len = bytes.length;
		StringBuilder buf = new StringBuilder(len * 2);
		// 把密文转换成十六进制的字符串形式
		for (int j = 0; j < len; j++) {
			buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
			buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
		}
		return buf.toString();
	}
}
